﻿using Enums;
using Microsoft.AspNetCore.Mvc;
using Model.Entity;
using Model.Request;
using Model.Response;
using Newtonsoft.Json;
using TemplateInterfaceService;
using Untils;

namespace Template_Api.Controllers
{
    /// <summary>
    /// 登录控制器
    /// </summary>    
    [ApiController]
    [Route("api/[controller]/[action]")]//路由规则
    [ApiExplorerSettings(GroupName = nameof(ApiVersionInfo.v1))]//Swagger版本
    public class LoginController : ControllerBase
    {                
        private readonly IJwtService _jwtService;//JWT服务
        private readonly IUserService _userService;//用户服务
        private readonly ILogger<LoginController> _logger;//日志服务

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="logger"></param>
        /// <param name="userService"></param>
        /// <param name="jwtService"></param>
        public LoginController(ILogger<LoginController> logger, IUserService userService, IJwtService jwtService)
        {
            _logger = logger;
            _jwtService = jwtService;
            _userService = userService;            
        }

        /// <summary>
        /// 登录
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<LoginResponse<Tokens>> Login(LoginRequest req)
        {
            try
            {                
                if (ModelState.IsValid)
                {
                    LoginResponse<Tokens> res = new LoginResponse<Tokens>();
                    Users user = await _userService.GetUser(req);
                    if (user == null)
                        return ApiResponseHelper.ErrorMessage<Tokens, LoginResponse<Tokens>>(SystemCode.LOGIN_ERROR_EMPTY, ApiResponseHelper.GetDescription(SystemCode.LOGIN_ERROR_EMPTY), null);

                    string token = await _jwtService.GetJwtToken(user);
                    return ApiResponseHelper.SucessMessage<Tokens, LoginResponse<Tokens>>(ApiResponseHelper.GetDescription(SystemCode.SUCCESS), new Tokens { accessToken = token });
                }
                else
                    return ApiResponseHelper.ErrorMessage<Tokens, LoginResponse<Tokens>>(SystemCode.LOGIN_CHECK_EMPTY, ApiResponseHelper.GetDescription(SystemCode.LOGIN_CHECK_EMPTY), null);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, LogMessage.PROCESS_ACTION_ERROR, RouteData.Values[RoutData.controller], RouteData.Values[RoutData.action]);
                return ApiResponseHelper.ErrorMessage<Tokens, LoginResponse<Tokens>>(SystemCode.SYSTEM_ERROR, ApiResponseHelper.GetDescription(SystemCode.SYSTEM_ERROR), null);
            }
        }
    }
}
